/*
 * Copyright 2015-2025 APP TEAM. All rights reserved.
 * Support: @Support
 * License: @License
 */
package com.zxl.admin.interceptor;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zxl.admin.context.UserContext;
import com.zxl.common.exception.AuthenticationException;
import com.zxl.common.model.pojo.SysUser;
import com.zxl.common.service.SysUserService;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;

/**
 * token拦截器
 */
@Component
public class ApiTokenInterceptor implements HandlerInterceptor {
    @Resource
    private SysUserService sysUserService;

    /**
     * Authorization头名称
     */
    public static final String TOKEN_NAME = "api-access-token";

    /**
     * 拦截请求，无token返回
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        UserContext.clearContext();
        StpUtil.checkLogin();
//        String token = request.getHeader(TOKEN_NAME);
//        SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>()
//                .eq("token",token));
        SysUser sysUser = sysUserService.getById(Integer.valueOf("" + StpUtil.getLoginId()));
        if (sysUser == null) {
            throw new AuthenticationException(AuthenticationException.INVALID_TOKEN);
        }
        UserContext.setUserId(sysUser.getId());
        UserContext.setUser(sysUser);
        request.setAttribute("userId", sysUser.getId());

        return true;
    }

    /**
     * 清空用户上下文
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserContext.clearContext();
    }

}

